//
//  HttpRequest.m
//  POS
//
//  Created by 廉英雷 on 15/9/24.
//  Copyright © 2015年 廉英雷. All rights reserved.
//

#import "HttpRequest.h"
#import "Tools.h"
#import "SVProgressHUD.h"
#import "UIDevice-Reachability.h"
#import "KVNProgress.h"
@interface HttpRequest ()

@property(nonatomic,strong)NSString * urlString;//请求url

@end

@implementation HttpRequest

- (void) getURL:(NSString *) url
 withDictionary:(NSDictionary *)dict
     httpHeader:(NSDictionary *)httpHeader
  receiveTarget:(id)target;
{
      [self configHttpRequest:url httpHeader:httpHeader receiveTarget:target];
      
      
      [self.sessManager GET:self.urlString parameters:dict success:^ void(NSURLSessionDataTask * task, id responseObject) {
            //[self requestFinished:responseObject] ;
            
            [self requestFinished:responseObject sender:target];
            
      } failure:^ void(NSURLSessionDataTask * task, id responseObject,NSError * error) {
                 //   [self requestFailed:error sender:target];
            [self responseErrorData:responseObject error:error sender:target];
            
      }];
      
}

- (void) putURL:(NSString *) url
 withDictionary:(NSDictionary *)dict
     httpHeader:(NSDictionary *)httpHeader
  receiveTarget:(id)target;
{
      [self configHttpRequest:url httpHeader:httpHeader receiveTarget:target];
      
      
      [self.sessManager PUT:self.urlString parameters:dict success:^ void(NSURLSessionDataTask * task, id responseObject) {
            [self requestFinished:responseObject sender:target] ;
            
      } failure:^ void(NSURLSessionDataTask * task,id responseObject ,NSError * error) {
                  //  [self requestFailed:error sender:target];
            [self responseErrorData:responseObject error:error sender:target];
      }];
}

- (void) postURL:(NSString *) url
  withDictionary:(NSDictionary *)dict
      httpHeader:(NSDictionary *)httpHeader
   receiveTarget:(id)target;
{
      [self configHttpRequest:url httpHeader:httpHeader receiveTarget:target];
      
      
      [self.sessManager POST:self.urlString parameters:dict success:^ void(NSURLSessionDataTask * task, id responseObject) {
            
            [self requestFinished:responseObject sender:target] ;
            
      } failure:^ void(NSURLSessionDataTask * task, id responseObject,NSError * error) {
            
            [self responseErrorData:responseObject error:error sender:target];
                    [self requestFailed:error sender:target];
             //       NSHTTPURLResponse
            
      }];
}



-(void)configHttpRequest:(NSString *) urlString
              httpHeader:(NSDictionary *)header
           receiveTarget:(id)target
{
      if (![UIDevice networkAvailable])
      {
            
            [[Tools shareTools] alert:@"网络请求失败" :@"请检查手机网络设置."];
            
            
                    [[Tools shareTools] stopLoading];
      }else{
            
            
            //转换需要提交的数据变为json
            
            
            NSLog(@"url======%@",urlString);
            self.urlString=[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            
            self.sessManager = [AFHTTPSessionManager manager];
            self.sessManager.requestSerializer = [AFJSONRequestSerializer serializer];

            self.sessManager.responseSerializer = [[AFHTTPResponseSerializer alloc] init];
            
            NSLog(@"-------序列化");
            [header enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
                  [self.sessManager.requestSerializer setValue:obj forHTTPHeaderField:key];
                  
            }];
            //NSLog(@"httpHeader======%@",self.sessManager.requestSerializer.HTTPRequestHeaders);
            
            self.sessManager.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
            //        self.sessManager.securityPolicy.allowInvalidCertificates = YES;
            //        self.sessManager.securityPolicy.validatesDomainName = NO;
            //        self.sessManager.securityPolicy.validatesCertificateChain = NO;
            self.sessManager.requestSerializer.timeoutInterval = 180;
            
      }
      
}

//7.30 新添加的方法，把sender传递进去，不使用self.sender
- (void)requestFinished:(id)responseObject sender:(NSString *)sender
{
      
      @try
      {
            [[Tools shareTools] stopLoading];
            
            NSData *responseData = responseObject;
            NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
            
            NSLog(@"responseString=====%@",responseString);
            
            //判断服务是否停止或者报错
            if ([responseString rangeOfString:@"<HTML>"].length > 0)
            {
                  [self.delegate serverFault];
            }
            else
            {
                  NSDictionary *receiveData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:nil];
                  
                  if ([self.delegate respondsToSelector:@selector(finishedRequest:withSender:)])
                  { [self.delegate finishedRequest:receiveData withSender:sender]; }
            }
            
      }
      @catch (NSException *exception) {
            NSLog(@"error is %@",exception.description);
      }
      
}


-(void)responseErrorData:(NSData *)response error:(NSError *)error sender:(NSString *)target
{
      [[Tools shareTools] stopLoading];
      NSString * errorMessage=[error localizedDescription];
      NSLog(@"errorMessage======%@",errorMessage);
      
      if (self.requestCancel)
      {
            self.requestCancel = NO;
            return;
      }
      
      
      
      if(!response){
            [self requestFailed:error sender:target];
            return;
      }
      
      NSLog(@"response string ======%@",[[NSString alloc]initWithData:response encoding:NSUTF8StringEncoding]);
      
      NSError * jsonError;
      NSDictionary * errorDict=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableContainers error:&jsonError];
      
      NSLog(@"nerrorInfo=========%@",errorDict);
      if ([errorMessage isEqualToString:@"Request failed: unimplemented (501)"]) {
            [SVProgressHUD showSuccessWithStatus:@"您现在还不是商户请注册"];
            //            [NSKeyedArchiver archiveRootObject:nil toFile:UserInfoDataFile];//返回403的时候清空用户信息，需要重新登录
            //            [Tools shareTools].user=nil;
            
            return;
      }
      
      if([errorMessage containsString:@"403"]){//特殊处理用户tockenId失效问题
            
            [SVProgressHUD showSuccessWithStatus:@"您的信息已过期，请重新登录！"];
//            [NSKeyedArchiver archiveRootObject:nil toFile:UserInfoDataFile];//返回403的时候清空用户信息，需要重新登录
//            [Tools shareTools].user=nil;
            
            return;
      }
      
      
      if (jsonError) {
            NSLog(@"json ========%@",jsonError.description);
      }else{
            
            if (self.delegate&&[self.delegate respondsToSelector:@selector(errorRequestDictionary:withSender:)]) {
                  [self.delegate errorRequestDictionary:errorDict withSender:target];
            }
            
            if([errorDict isKindOfClass:[NSDictionary class]]){
                  if (errorDict[@"message"]&&![target isEqualToString:@"setpassword-phoneexist"]) {//特殊处理一些请求
                        
                        [[Tools shareTools] alert:errorDict[@"message"] :nil];//如果有信息直接显示
                        
                        return;
                        
                  }
            }else{
                  
                  [[Tools shareTools] alert:[[(NSArray *)errorDict firstObject] objectForKey:@"message"] :nil];//有时会返回错误数组，取第一个错误信息显示
            }
            
      }
      
      [self requestFailed:error sender:target];
      
      
      
}

- (void)requestFailed:(NSError *)error sender:(NSString *)target
{
      [KVNProgress dismiss];
      
      NSString* errorMessage = [error localizedDescription];
      if ([errorMessage isEqualToString:@"Request failed: unimplemented (501)"]) {
            
            
           // [[Tools shareTools] alert:@"系统繁忙,请稍后再试!" :nil];
            return;

      }
      if ([errorMessage containsString:@"502"]) {
            
            [[Tools shareTools] alert:@"系统繁忙,请稍后再试!" :nil];
            return;
            
      } if ([errorMessage containsString:@"501"]) {
            
            [[Tools shareTools] alert:@"系统繁忙,请稍后再试!" :nil];
            return;
            
      }

      
      @try {
            if (self.delegate) {
                  
                  [self.delegate errorRequest:error withSender:target];
            }    }
      @catch (NSException *exception) {
            
            NSLog(@"error is %@",exception.description);
      }
      
      
}
-(void)errorRequest:(NSError *)error withSender:(NSString *)sender
{
      NSString * errorString=[error localizedDescription];
      // NSLog(@"%@",error.userInfo);
      if ([errorString containsString:@"422"]) {
            [[Tools shareTools] alert:@"修改失败!" :nil];
      }
      //           else if ([errorString containsString:@"501"]){
      //            [[Tools shareTools] alert:@"用户名或密码不正确!" :nil];
      //      }
      
      
}


@end
